package com.springcloud.tools.aop;

import com.springcloud.tools.exception.IdempotentException;
import com.springcloud.tools.token.TokenService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author fuc
 * @create 2020-08-21
 */
@Component
@Aspect
public class IdempotentAspect {
  @Autowired TokenService tokenService;

  @Pointcut("@annotation(com.springcloud.tools.annotation.AutoIdempotent)")
  public void pointcut() {}

  @Before("pointcut()")
  public void before(JoinPoint joinPoint) throws IdempotentException {

    HttpServletRequest request =
        ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

    try {
      tokenService.checkToken(request);
    } catch (IdempotentException e) {
      throw e;
    }
  }
}
